import { Device } from "@bidiao/framework";
import { ContextRender } from "./ContextRender";
// 倾斜角度
const ANGLE = 30;
const SHADOWBLUR = 5;
// 生成随机长度
function randomLength() {
  return Math.random() * 80 + (Device.Mobile ? 80 : 150);
}
// 生成随机透明度
function randomOpacity() {
  return Math.random() * 0.5 + 0.5;
}
// 生成随机速度
function randomSpeed() {
  return Math.random() * 2 + (Device.Mobile ? 1.5 : 2);
}
// 生成随机线宽
function randomLineWidth() {
  return Math.random() * 0.8 + 0.5;
}

export default class RainStar extends ContextRender {
  /** 长度 */
  length: number;
  /** 流星的线宽 */
  lineWidth = randomLineWidth();
  /** 流星划过的速度 */
  speed = randomSpeed();

  get startPoint() {
    return {
      x: this.options.shadowBlur,
      y: this.options.height - this.options.shadowBlur,
    };
  }
  get endPoint() {
    return {
      x: this.options.width - this.options.shadowBlur,
      y: this.options.shadowBlur,
    };
  }
  get speedOffsetX() {
    return this.speed * Math.cos((ANGLE * Math.PI) / 180);
  }
  get speedOffsetY() {
    return this.speed * Math.sin((ANGLE * Math.PI) / 180);
  }

  /**
   *
   * @param point 初始化时的位置坐标
   * @param color 流星的颜色
   */
  constructor(point: { x: number; y: number }, color: string) {
    const length = randomLength();
    const x = (ANGLE * Math.PI) / 180;
    const width = length * Math.cos(x) + SHADOWBLUR * 2;
    const height = length * Math.sin(x) + SHADOWBLUR * 2;
    super(point, {
      width: width,
      height: height,
      opacity: randomOpacity(),
      shadowColor: "#fff",
      shadowBlur: SHADOWBLUR,
      color,
    });
    this.length = length;
    // 初始 Context 的一些绘制参数
    this.Context.lineWidth = this.lineWidth;
    // 绘制流星线段的过渡颜色
    const rainLine = this.Context.createLinearGradient(0, this.options.height, this.options.width, 0);
    rainLine.addColorStop(0, color);
    rainLine.addColorStop(1, "rgba(255,255,255,0)");
    this.Context.strokeStyle = rainLine;
  }

  protected render(context: CanvasRenderingContext2D) {
    this.options.opacity -= Math.random() / 500;

    context.save();
    context.beginPath();
    context.globalAlpha = this.options.opacity;
    // 起点
    context.moveTo(this.startPoint.x, this.startPoint.y);
    // 终点
    context.lineTo(this.endPoint.x, this.endPoint.y);
    context.closePath();
    context.stroke();

    context.restore();

    this.point.x -= this.speedOffsetX;
    this.point.y += this.speedOffsetY;

    if (this.options.opacity <= 0.05) {
      this.destory();
    }
  }
}
